package com.work.music.service;

import com.work.music.common.EmailSend;
import com.work.music.common.HttpRequestParamter;
import com.work.music.common.ResponseJson;
import com.work.music.dao.IntegralMapper;
import com.work.music.dao.MusicPhonecodeMapper;
import com.work.music.dao.MusicUserMapper;
import com.work.music.dao.SystemSetMapper;
import com.work.music.entity.Integral;
import com.work.music.entity.MusicPhonecode;
import com.work.music.entity.MusicUser;
import com.work.music.entity.SystemSet;
import com.work.music.exception.AjaxOperationFailException;
import com.work.music.utils.HexString;
import com.work.music.utils.HttpUtil;
import com.work.music.utils.PhoneCode;
import com.work.music.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService extends BaseService {
    @Autowired
    private MusicUserMapper musicUserMapper;
    @Autowired
    private MusicPhonecodeMapper musicPhonecodeMapper;
    @Autowired
    private SystemSetMapper systemSetMapper;
    @Autowired
    private EmailSend emailSend;
    @Autowired
    private IntegralMapper integralMapper;

    /**
     *
     * @return
     */
    public ResponseJson getPhoneCode() throws AjaxOperationFailException {
        String phone = HttpRequestParamter.getString("phone");//手机号或邮箱
        int type = HttpRequestParamter.getInt("type");  //类型（0：注册  1：忘记密码  2：三方绑定）
        long uid = HttpRequestParamter.getUid(); //登录用户id
        if(StringUtil.isNull(phone)) {
            throw new AjaxOperationFailException("请输入手机号或邮箱");
        }
        if(!StringUtil.isPhone(phone) && !StringUtil.isEmail(phone)) {
            throw new AjaxOperationFailException("请输入正确的手机号或邮箱");
        }
        if(PhoneCode.isFrequently(redisSession, phone, type + "")) {
            throw new AjaxOperationFailException("请勿重复获取");
        }
        ResponseJson responseJson = new ResponseJson();
        if(type == 2 && uid != 0) {
            responseJson.setStatus(101);
            responseJson.setMsg("请登录后再操作！");
            return responseJson;
        }

        MusicUser musicUser = musicUserMapper.selectByPhoneOrEmail(phone);
        if(musicUser != null && (type == 0 || type == 2)) {
            throw new AjaxOperationFailException("该手机号或邮箱已被注册");
        } else if(musicUser == null && type == 1) {
            throw new AjaxOperationFailException("该手机号或邮箱未注册");
        }

        int yzcodType = 0;
        String yzcode = StringUtil.getRandomString(6, 2);
        if(StringUtil.isPhone(phone)) {

            //类型（0：手机注册  1：邮箱注册  2：手机忘记密码  3：邮箱忘记密码   4：三方绑定手机  5：三方绑定邮箱）
           switch (type) {
               case 0:
                   yzcodType = 0;
                   break;
               case 1:
                   yzcodType = 2;
                   break;
               case 2:
                   yzcodType = 4;
                   break;
           }
        } else if(StringUtil.isEmail(phone)) {
            SystemSet systemSet = systemSetMapper.selectByPrimaryKey(1L);
            if (systemSet != null && systemSet.getStatus() == 1) {
                emailSend.sendEmailCode(phone, yzcode, type);
            }
            switch (type) {
                case 0:
                    yzcodType = 1;
                    break;
                case 1:
                    yzcodType = 3;
                    break;
                case 2:
                    yzcodType = 5;
                    break;
            }
        }

        MusicPhonecode musicPhonecode = new MusicPhonecode();
        musicPhonecode.setAddip(HttpUtil.getClientIp());
        musicPhonecode.setAddtime(new Date());
        musicPhonecode.setPhone(phone);
        musicPhonecode.setType(yzcodType);
        musicPhonecode.setYzcode(yzcode);
        int tag = musicPhonecodeMapper.insert(musicPhonecode);
        if(tag <= 0) {
            throw new AjaxOperationFailException("数据库操作失败");
        }

        /**
         * 删除缓存中的信息，在新增
         */
        PhoneCode.removeYzcode(redisSession, phone);
        PhoneCode.addPhoneCode(redisSession, phone, type, yzcode);

        return new ResponseJson();
    }

    public ResponseJson register() throws AjaxOperationFailException {
        String phone = HttpRequestParamter.getString("phone");
        String yzcode = HttpRequestParamter.getString("yzcode");
        String userpwd = HttpRequestParamter.getString("userpwd");

        if(StringUtil.isNull(phone)) {
            throw new AjaxOperationFailException("请输入手机号或邮箱地址");
        }
        if(StringUtil.isNull(yzcode)) {
            throw new AjaxOperationFailException("请输入验证码");
        }
        if(StringUtil.isNull(userpwd)) {
            throw new AjaxOperationFailException("请输入密码");
        }
        if(!StringUtil.isPhone(phone) && !StringUtil.isEmail(phone)) {
            throw new AjaxOperationFailException("请输入正确的手机号或邮箱");
        }
        int result = PhoneCode.yzcode(redisSession, phone, "0", yzcode);
        if(result == -1) {
            throw new AjaxOperationFailException("验证码已过期");
        } else if(result == -2) {
            throw new AjaxOperationFailException("验证码错误");
        }

        MusicUser musicUser = musicUserMapper.selectByPhoneOrEmail(phone);
        if(musicUser != null) {
            throw new AjaxOperationFailException("该手机号或邮箱已被注册");
        }
        musicUser = new MusicUser();
        musicUser.setEmail(StringUtil.isEmail(phone) ? phone : "");
        musicUser.setUserName(phone);
        musicUser.setPhone(StringUtil.isPhone(phone) ? phone : "");
        musicUser.setUserPwd(StringUtil.md5(userpwd));
        musicUser.setRegisterIp(HttpUtil.getClientIp());
        musicUser.setRegisterTime(new Date());
        musicUser.setRegisterType(StringUtil.isPhone(phone) ? 0 : 1);
        musicUser.setIsdisabled(1);
        musicUser.setState(0);
        int tag = musicUserMapper.insert(musicUser);
        if(tag <= 0) {
            throw new AjaxOperationFailException("注册失败");
        }

        //todo 判断是否是手机号，若是手机号发送短信通知，若是邮箱，则发送邮件通知
        /*if(StringUtil.isPhone(phone)) {

        } else {

        }*/

        //删除缓存中的数据
        PhoneCode.removeYzcode(redisSession, phone);

        return new ResponseJson();
    }

    /**
     * 登录
     * @return
     */
    public ResponseJson login() throws AjaxOperationFailException {
        String username = HttpRequestParamter.getString("phone");  //用户名
        String userpwd = HttpRequestParamter.getString("userpwd"); //密码
        if(StringUtil.isNull(username)) {
            throw new AjaxOperationFailException("请输入手机号或邮箱地址！");
        }
        if(StringUtil.isNull(userpwd)) {
            throw new AjaxOperationFailException("请输入密码！");
        }
        MusicUser musicUser = musicUserMapper.selectByPhoneOrEmail(username);
        if(musicUser == null) {
            throw new AjaxOperationFailException("该用户不存在！");
        }
        if(!StringUtil.md5(userpwd).equals(musicUser.getUserPwd())) {
            throw new AjaxOperationFailException("密码错误！");
        }

        String token = StringUtil.getUUid();
        token = HexString.encode(token);

        //删除之前同一登录用户的缓存信息
        List<String> list = PhoneCode.removeUser(redisSession, username, musicUser.getId());
        if(StringUtil.isListNull(list)) {
            list = new ArrayList<>();
        }
        list.add(token);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uid", musicUser.getId());

        redisSession.setMapValue(token, map, 10, TimeUnit.DAYS);
        redisSession.setListValue("userList", list, 10, TimeUnit.DAYS);
        ResponseJson responseJson = new ResponseJson();
        responseJson.setMsg("登录成功");
        responseJson.setObj(token);
        //将当前用户存入缓存中
        return responseJson;
    }

    /**
     * 获取用户个人资料
     * @return
     * @throws AjaxOperationFailException
     */
    public ResponseJson getUserInfo() throws AjaxOperationFailException {
        ResponseJson responseJson = new ResponseJson();
        long uid = HttpRequestParamter.getUid();
        MusicUser musicUser = musicUserMapper.selectByPrimaryKey(uid);
        if(musicUser == null) {
            throw  new AjaxOperationFailException("未找到该用户信息");
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userName", StringUtil.isNull(musicUser.getUserName()) ? "" : musicUser.getUserName());
        map.put("email", StringUtil.isNull(musicUser.getEmail()) ? "" : musicUser.getEmail());
        map.put("phone", StringUtil.isNull(musicUser.getPhone()) ? "" : musicUser.getPhone());
        map.put("headimg", StringUtil.isNull(musicUser.getHeadimg()) ? "" : StringUtil.IMGURL + musicUser.getHeadimg());
        map.put("nickName", StringUtil.isEmpty(musicUser.getNickName()) ? "" : musicUser.getNickName());
        map.put("userDesc", StringUtil.isEmpty(musicUser.getUserDesc()) ? "" : musicUser.getUserDesc());

        //获取用户积分，若无积分信息，则新增
        Integral integral = integralMapper.selectByPrimaryKey(uid);
        if (integral == null) {
            map.put("integral", 0);
            integral = new Integral();
            integral.setUid(uid);
            integral.setUseintegral(0L);
            integral.setTotalintegral(0L);
            integralMapper.insert(integral);
        } else {
            map.put("integral", integral.getUseintegral());
        }

        responseJson.setMsg("获取成功");
        responseJson.setObj(map);
        return responseJson;
    }

    /**
     * 修改用户个人资料
     * @return
     */
    public ResponseJson editUserInfo() throws AjaxOperationFailException {
        long uid = HttpRequestParamter.getUid();
        String headimg = HttpRequestParamter.getString("headimg");
        String nickname = HttpRequestParamter.getString("nickname");
        String userDesc = HttpRequestParamter.getString("userDesc");
        MusicUser musicUser = musicUserMapper.selectByPrimaryKey(uid);
        if(musicUser == null) {
            throw new AjaxOperationFailException("未找到该用户信息！");
        }
        if(!StringUtil.isNull(headimg)) {
            musicUser.setHeadimg(headimg.replace(StringUtil.IMGURL, ""));
        }
        if(!StringUtil.isEmpty(nickname)) {
            musicUser.setNickName(nickname);
        }
        if(!StringUtil.isEmpty(userDesc)) {
            musicUser.setUserDesc(userDesc);
        }
        int tag = musicUserMapper.updateByPrimaryKey(musicUser);
        if(tag <= 0) {
            throw new AjaxOperationFailException("修改失败");
        }
        return new ResponseJson();
    }

    /**
     * 忘记密码
     * @return
     * @throws AjaxOperationFailException
     */
    public ResponseJson forgetPwd() throws AjaxOperationFailException {
        String phone = HttpRequestParamter.getString("phone");
        String yzcode = HttpRequestParamter.getString("yzcode");
        String userpwd = HttpRequestParamter.getString("userpwd");

        if(StringUtil.isNull(phone)) {
            throw new AjaxOperationFailException("请输入手机号或邮箱地址");
        }
        if(StringUtil.isNull(yzcode)) {
            throw new AjaxOperationFailException("请输入验证码");
        }
        if(StringUtil.isNull(userpwd)) {
            throw new AjaxOperationFailException("请输入密码");
        }
        if(!StringUtil.isPhone(phone) && !StringUtil.isEmail(phone)) {
            throw new AjaxOperationFailException("请输入正确的手机号或邮箱");
        }
        int result = PhoneCode.yzcode(redisSession, phone, "1", yzcode);
        if(result == -1) {
            throw new AjaxOperationFailException("验证码已过期");
        } else if(result == -2) {
            throw new AjaxOperationFailException("验证码错误");
        }

        MusicUser musicUser = musicUserMapper.selectByPhoneOrEmail(phone);
        if(musicUser == null) {
            throw new AjaxOperationFailException("该手机号或邮箱未被注册");
        }
        musicUser.setUserPwd(StringUtil.md5(userpwd));
        musicUser.setIsdisabled(1);
        int tag = musicUserMapper.updateByPrimaryKey(musicUser);
        if(tag <= 0) {
            throw new AjaxOperationFailException("修改失败");
        }

        //todo 判断是否是手机号，若是手机号发送短信通知，若是邮箱，则发送邮件通知
        /*if(StringUtil.isPhone(phone)) {

        } else {

        }*/

        //删除缓存中的数据
        PhoneCode.removeYzcode(redisSession, phone);

        return new ResponseJson();
    }
}
